﻿using GKQC.Common;
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace GKQC.Machine
{
    /// <summary>
    /// 自動測試LC仪器
    /// </summary>
    public class LcMeter1601: ILcMeter
    {
        public string Prefix { get; set; }
        public void ControlMachine(SerialPort sp)
        {
            if (sp != null && !sp.IsOpen) { sp.Open(); Thread.Sleep(50); }
            byte[] SendBytes = null;
            string SendData = "*RMT" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据 
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                }
            }
        }

        public void UnControlMachine(SerialPort sp)
        {
            if (sp != null && !sp.IsOpen) { sp.Open(); Thread.Sleep(50); }
            byte[] SendBytes = null;
            string SendData = "*END" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据 
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                }
            }
        }

        public void SetLeak(SerialPort sp, string leak)
        {

            string SendData = "PROG:LEAK" + leak + Environment.NewLine;
            byte[] SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            Thread.Sleep(200);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                                                          //Thread.Sleep(50);
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据 
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                }
            }
        }

        public void SetVoltage(SerialPort sp, decimal voltage)
        {
            string SendData = "PROG:VOLT" + voltage.ToString() + Environment.NewLine;
            byte[] SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            Thread.Sleep(200);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                Thread.Sleep(200);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                }
            }
        }

        public void SetCharTime(SerialPort sp, decimal chargeTime)
        {
            string SendData = "PROG:CHAR" + chargeTime.ToString() + Environment.NewLine;
            byte[] SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            Thread.Sleep(200);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                    result = GetData(sp);
                    if (!result.Contains("0,OK"))
                    {
                        Thread.Sleep(200);
                        sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                    }
                }
            }
        }

        public void SetDisChargeTime(SerialPort sp, decimal disChargeTime)
        {
            string SendData = "PROG:DISC" + disChargeTime.ToString() + Environment.NewLine;
            byte[] SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            Thread.Sleep(200);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                }
            }
        }

        void ILcMeter.SetTestTime(SerialPort sp, decimal testTime)
        {
            string SendData = "PROG:TEST" + testTime.ToString() + Environment.NewLine;
            byte[] SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            Thread.Sleep(200);
            sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                    result = GetData(sp);
                    if (!result.Contains("0,OK"))
                    {
                        Thread.Sleep(200);
                        sp.Write(SendBytes, 0, SendBytes.Length);//发送数据
                    }
                }
            }
        }

        public void Char(SerialPort sp)
        {
            byte[] SendBytes = null;
            Thread.Sleep(200);
            string SendData = "CHAR" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                }
            }
        }

        public void DisCharge(SerialPort sp)
        {
            if (sp != null && !sp.IsOpen) { sp.Open(); Thread.Sleep(50); }
            byte[] SendBytes = null;
            string SendData = "DISC" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            Thread.Sleep(50);
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                Thread.Sleep(50);
                result = GetData(sp);
                sp.DiscardInBuffer();
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                }
            }
        }

        public void Test(SerialPort sp)
        {
            byte[] SendBytes = null;
            string SendData = "TEST" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据

            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据

                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                }
            }
        }

        public int GetChargeTime(SerialPort sp)
        {
            int time = 60;
            byte[] SendBytes = null;
            string SendData = "PROG:CHAR?" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            Thread.Sleep(50);
            string result = GetData(sp).Trim().Replace("\r\n", string.Empty);
            if (!int.TryParse(result.Trim(), out time))
            {
                //Logger.LogMessage("獲取充電時間錯誤：" + result);
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                result = GetData(sp).Trim().Replace("\r\n", string.Empty);
                if (!int.TryParse(result.Trim(), out time))
                {
                    //Logger.LogMessage("獲取充電時間錯誤：" + result);
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                    result = GetData(sp).Trim().Replace("\r\n", string.Empty);
                    if (!int.TryParse(result.Trim(), out time))
                    {
                        //Logger.LogMessage("獲取充電時間錯誤：" + result);
                        Thread.Sleep(200);
                        sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                    }
                }
            }

            if (time > 10) time = time - 2;
            return time;
            //Logger.LogMessage("充電時間：" + result);
        }

        public int GetTestTime(SerialPort sp)
        {
            int time = 0;
            byte[] SendBytes = null;
            string SendData = "PROG:TEST?" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            Thread.Sleep(50);
            string result = GetData(sp).Trim().Replace("\r\n", string.Empty);
            if (!int.TryParse(result.Trim(), out time))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                result = GetData(sp).Trim().Replace("\r\n", string.Empty);
                if (!int.TryParse(result.Trim(), out time))
                {
                    Thread.Sleep(200);
                    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                    result = GetData(sp).Trim().Replace("\r\n", string.Empty);
                    if (!int.TryParse(result.Trim(), out time))
                    {
                        Thread.Sleep(200);
                        sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                    }
                }
            }
            return time;
        }

        //public decimal GetVoltage(SerialPort sp)
        //{
        //    int voltage = 0;
        //    byte[] SendBytes = null;
        //    string SendData = "PROG:VOLT?" + Environment.NewLine;
        //    SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
        //    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
        //    string result = GetData(sp).Trim().Replace("\r\n", string.Empty);
        //    //50.0 50.0 50.0
        //    if (!int.TryParse(result.Trim(), out voltage))
        //    {
        //        Thread.Sleep(200);
        //        sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
        //        result = GetData(sp).Trim().Replace("\r\n", string.Empty);
        //        if (!int.TryParse(result.Trim(), out voltage))
        //        {
        //            Thread.Sleep(200);
        //            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
        //            result = GetData(sp).Trim().Replace("\r\n", string.Empty);
        //            if (!int.TryParse(result.Trim(), out voltage))
        //            {
        //                Thread.Sleep(200);
        //                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
        //            }
        //        }
        //    }
        //    return voltage;
        //}

        public string GetData(SerialPort sp)
        {
            try
            {
                byte[] readBuffer = new byte[sp.BytesToRead];
                sp.Read(readBuffer, 0, readBuffer.Length);
                return System.Text.Encoding.ASCII.GetString(readBuffer);
            }
            catch (IOException IOEx)
            {
                Logger.LogError(IOEx);
            }
            catch (InvalidOperationException IVOEx)
            {
                Logger.LogError(IVOEx);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            return "";
        }

        public List<double> AnalysisData(string rawData)
        {
            List<double> list = new List<double>();
            for (int i = 0; i < 10; i++)
            {
                list.Add(0d); 
            }

            if (!string.IsNullOrWhiteSpace(rawData))
            {
                //1:0.0000uA2:0.0000uA3:0.0000uA4:0.0000uA5:0.0000uA6:0.0000uA7:0.0000uA8:0.0000uA9:0.0000uA10:0.000uA 
                string[] trings1 = rawData.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                if (trings1 == null || trings1.Length == 0) return list;

                int rightIndex = -1;
                for (int i = trings1.Length - 1; i > -1; i--)
                {
                    if (string.IsNullOrWhiteSpace(trings1[i])) continue;
                    if (trings1[i].Contains("A") && trings1[i].Split('A').Length >=11)
                    {
                        rightIndex = i;
                        break;
                    }
                }

                if (rightIndex == -1) return list;


                double times = 1;
                if (trings1[rightIndex].Contains("mA"))
                    times = 1000;
                else if (trings1[rightIndex].Contains("uA"))
                    times = 1;

                string[] strings = trings1[rightIndex].Split('A');//1:0.0000u
                if (strings == null || strings.Length < 11) return list;
                for(int i= 0;i< strings.Length; i++)
                {
                    //if (string.IsNullOrEmpty(strings[i])) continue;
                    //string[] oneString = strings[i].Split(':');
                    //if (oneString == null || oneString.Length != 2) continue;
                    //double value = 0;
                    //if (double.TryParse(oneString[1].Replace("u", string.Empty).Replace("m", string.Empty), out value))
                    //    list.Add(Math.Round(value* times,3));

                    //if (list.Count > 9) break;

                    if (string.IsNullOrEmpty(strings[i])) continue;
                    string[] oneString = strings[i].Split(':');
                    if (oneString == null || oneString.Length != 2) continue;
                    double value = 0;
                    int index = 0;
                    if (index > 10) continue;
                    int.TryParse(oneString[0].Trim(), out index);
                    if (double.TryParse(oneString[1].Replace("u", string.Empty).Replace("m", string.Empty), out value))
                        list[index-1] = Math.Round(value * times, 3);
                }
            }

            return list;
        }

        /// <summary>
        /// 10通道LC測試用來獲取LC值的
        /// </summary>
        /// <param name="sp"></param>
        public string GetLeak(SerialPort sp, string add)
        {
            byte[] SendBytes = null;
            string SendData = "LEAK" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            //Thread.Sleep(50);
            return GetData(sp);
        }

        public decimal GetVoltage(SerialPort sp)
        {
            if (sp != null && !sp.IsOpen) { sp.Open(); Thread.Sleep(50); }
            decimal voltage = 0;
            byte[] SendBytes = null;
            string SendData = "VOLT?" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            Thread.Sleep(50);
            string result = GetData(sp).Trim().Replace("\r\n", string.Empty);
            //0.1V,0.0000
            if (!result.Contains("V")) return 0;
            string[] ss = result.Split(',');
            if (ss.Length < 2) return 0;

            string voltageString = string.Empty;
            for(int i=0; i<ss.Length-1; i++)
            {
                if(ss[i].Contains("V"))
                {
                    if (ss[i].Contains("A"))
                    {
                        voltageString = ss[i].Substring(ss[i].IndexOf("A")).Replace("V",string.Empty);
                    }
                    else
                    {
                        voltageString = ss[i].Replace("V", string.Empty);
                    }

                    if (decimal.TryParse(voltageString, out voltage))
                    {
                        if (voltage > 0) break;
                    }
                }
            }

            return voltage;
        }

        public bool Check(SerialPort sp)
        {
            bool flag = false;

            byte[] SendBytes = null;
            string SendData = "*RMT" + Environment.NewLine;
            SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
            sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
            Thread.Sleep(50);
            string result = GetData(sp);
            if (!result.Contains("0,OK"))
            {
                Thread.Sleep(200);
                sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据

                result = GetData(sp);
                if (!result.Contains("0,OK"))
                {
                    Thread.Sleep(250);
                    sp.Write(SendBytes, 0, SendBytes.Length);   //发送数据
                }
                else
                    flag = true;
            }
            else
                flag = true;

            return flag;
        }
    }
}
